<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>MCU Conference</title>
    <script type="text/javascript" src="js/SkyRTC-client.js"></script>
    <script type="text/javascript" src="js/jquery-1.10.2.js"></script>
    <script type="text/javascript" src="js/jquery-ui-1.10.1.min.js"></script>
    <script type="text/javascript" src="js/camerainfos.js"></script>
    <script type="text/javascript" src="js/common.js"></script>
    <script type="text/javascript" src="js/splitscreen.js"></script>
    <link href="css/main.css" rel="stylesheet" type="text/css"/>
    <script type="text/javascript">
        var rtc;
        var mcu = VideoMCU();   //分屏MCU

        var currRoomNum = "MsgRoom";//该房间专门用于发送消息
        var userID; //用户id
        var userName; //用户姓名
        var currVideoId; //当前正在使用的摄像头id

        var isAudioOn = false; //是否开启麦克风, 默认关闭

        function init() {
            console.log("开始初始化index.html");
            userID = request("userId");
            userName = request("userName");

            var fullUrl = location.href;
            console.log("完整访问的URL为" +  fullUrl);
            console.log("访问参数为" +  fullUrl.substring(fullUrl.indexOf("#") + 1));

            //初始化RTC相关的回调函数
            initRTC();
            connectWSServer();
            //初始化MCU分屏功能
            mcu.init({
                "defaultImgPath": "defaultConf.bmp",    //无视频时的默认图片路径
                "videoContainerId": "screenContainer",  //视频容器div
                "localVideoUserId": userID
            });

            var videoName = request("videoName");
            //去除字符串中的双引号
            videoName = videoName.replace(/"/g, "");

            //获取摄像头列表，并在获取后进行初始化
            initAndGetCameraInfos(function (videoInfos) {
                console.log("获取摄像头列表成功", videoInfos);
                //如果url中未指定摄像头，则自己指定
                if (videoName == null || videoName.length == 0) {
                    //获取摄像头列表的第一个摄像头，作为默认摄像头
                    currVideoId = getFreeCamId();
                } else {  //如果已指定，则需要根据名称获取摄像头id
                    currVideoId = getCameraIdByName(videoName);
                }

                if (currVideoId == null || currVideoId.length == 0) {
                    console.log("MCU初始化失败，因未获取到有效的摄像头");
                    return;
                }

//                if (currRoomNum != null && currRoomNum.length > 0) {
//                    join(currRoomNum);
//                }
            });
        }

        function initRTC() {
            console.log("开始初始化WebSocket连接");
            rtc = SkyRTC();

            //成功创建WebSocket连接
            rtc.on("socket_connected", function (socket) {
            });

            rtc.on("get_message", function(data){
                console.log("local.html收到文本消息：" + JSON.stringify(data));
                console.log("开始调用bound.JSVideoNum...");
                try {
                    bound.jSReceiveMsg(data.reqUser, data.reqMsg);
                    //bound.receiveMsg(reqUser, reqMsg);
                } catch (error) {
                    console.log("在调用bound.jsVideoNum时出错 + " + error);
                }
            });

            //断开WebSocket连接
            rtc.on("socket_closed", function(socket){
                console.log("WebSocket连接已断开，开始重置RTC与MCU", socket);
                //断开后重新初始化rtc，防止后面再次调用
                initRTC();
                //清理页面
                mcu.cleanUp();
                console.log("RTC与MCU重置完毕");
            });

            //创建本地视频流成功
            rtc.on("stream_created", function (stream) {
                var myVideoUrl = URL.createObjectURL(stream);
                var user1 = {"userId": userID, "userName": userName, "videoPosition": 1, "videoURL": myVideoUrl};

                //页面第一次加载，创建本地视频成功后，直接进行1分屏
                if(mcu.currVideoUsers.length == 0) {
                    mcu.SplitVideoScreen(1, [user1]);
                }else{  // 切换摄像头成功后，将本地用户新的视频地址更新到MCU中
                    mcu.updateUserVideo(user1);
                }
            });

            //创建本地视频流失败
            rtc.on("stream_create_error", function () {
                console.warn("创建本地视频流失败");
            });
        }

        //获取媒体相关属性，用于加载摄像头和麦克风
        function getMediaOptions(videoId, isAudioOn) {
            return {
                video: {
                    mandatory: {"maxWidth": "1920", "maxHeight": "1080"},
                    "optional": [{"sourceId": videoId}, {"frameRate": 60}, {"aspectRatio": 16 / 9}]
                },
                audio: isAudioOn
            };
        }

        //开启本地摄像头
        function openCamera(videoName){
            if (videoName == null || videoName.length == 0) {
                //获取摄像头列表的第一个摄像头，作为默认摄像头
                currVideoId = getFreeCamId();
            } else {  //根据名称获取摄像头id
                currVideoId = getCameraIdByName(videoName);
            }
            console.info("开启本地视频");
            rtc.createStreamAndInit(getMediaOptions(currVideoId, isAudioOn));
        }

        //关闭本地摄像头
        function closeCamera(){
            console.info("开始关闭本地视频");
            rtc.closeLocalStream();
            mcu.cleanUp();
        }
        
        function sendMsg(msg){
        	rtc.sendToServer(msg);
        }
        
        function lockUser(){
        	var msg = {
        			"eventName":"__lockuser",
        			"data":{"userId":userID}
        	};
        	sendMsg(JSON.stringify(msg));
        }
        
        function unlockUser(){
        	var msg = {
        			"eventName":"__unlockuser",
        			"data":{"userId":userID}
        	};
        	sendMsg(JSON.stringify(msg));
        }

        //连接WebSocket视频控制中心
        function connectWSServer() {
            console.log("开始连接WebSocket");
            if (!IsStringEmpty(currRoomNum)) {
                var webSocketType = isSecure()? "wss":"ws";
                //连接WebSocket服务器
                var wsUrl = webSocketType + ":" + window.location.href.substring(window.location.protocol.length).split('local.html')[0] + "msgserver";
                rtc.connect(wsUrl, currRoomNum, userID, userName);
                console.log("连接 WebSocket服务器:" + wsUrl, currRoomNum);
            } else {
                console.log("因参数中会议号为空，暂时不初始化websocket连接");
            }
        }

        //断开WebSocket链接
        function unconnectWSServer(){
            rtc.unConnect();
        }

        //获取视频数量
        function getVideosNumber() {
            return document.getElementsByTagName("video").length;
        }
        
        //用于向所有在线用户群发消息
        function broadcast(userId, msg){
        	var fullUrl = "broadcast?sendid="+userId+"&msgbody=" + msg;
            $.get(fullUrl, function(data,status){
                console.log("广播返回结果：" + data);
             });
        }
    </script>
</head>
<body onload="init();">
<div id="screenContainer"></div>
<input type="button" id="blockdebug" />
</body>
</html>
